<template>
  <view class="group-archive-container">
    <!-- 页面标题 -->
    <view class="page-header">
      <view class="page-title">集团档案管理</view>
      <view class="page-subtitle">共{{ totalGroups }}个集团单位</view>
    </view>

    <!-- 搜索和筛选区域 -->
    <view class="search-filter-area">
      <view class="search-box">
        <u-search
          v-model="searchKeyword"
          placeholder="搜索集团名称"
          height="40"
          showAction
          actionText="搜索"
          shape="round"
          bgcolor="#f8f9fc"
          @custom="onSearch"
          @search="onSearch"
        ></u-search>
      </view>

      <!-- 快速筛选标签 -->
      <scroll-view scroll-x class="filter-tags">
        <view class="tags-container">
          <view
            v-for="(tag, index) in filterTags"
            :key="index"
            class="filter-tag"
            :class="{ active: activeTagIndex === index, 'tag-with-shadow': activeTagIndex === index }"
            @click="filterByTag(index)"
          >
            <view class="tag-icon" :class="tag.class">
              <u-icon
                :name="tag.icon"
                :color="activeTagIndex === index ? '#ffffff' : tag.color"
                size="18"
              ></u-icon>
            </view>
            <text>{{ tag.name }}</text>
            <text class="tag-count">{{ tag.count }}</text>
          </view>
        </view>
      </scroll-view>

      <!-- 低质态筛选开关 -->
      <view class="low-quality-filter">
        <u-switch
          :value="isLowQualityFilter === 1"
          activeColor="#ff9900"
          @change="onLowQualityFilterChange"
        ></u-switch>
        <text class="low-quality-text">只看低质态单位</text>
        <text class="low-quality-count">{{ lowQualityCount }}</text>
      </view>
    </view>

    <!-- 集团列表区域 -->
    <view class="group-list-area">
      <scroll-view scroll-y class="group-list" v-if="filteredGroups.length > 0">
        <view
          v-for="(group, index) in filteredGroups"
          :key="index"
          class="group-card premium-card"
          @click="viewGroupDetail(group)"
        >
          <!-- 集团信息 -->
          <view class="group-info">
            <view class="group-avatar square-avatar" :class="getIndustryClass(group.industry)">
              <text>{{ group.name.substring(0, 1) }}</text>
            </view>
            <view class="group-details">
              <view class="group-name">{{ group.name }}</view>
              <view class="group-meta">
                <text class="group-district">{{ group.district }}</text>
                <text class="group-industry">{{ group.industry }}</text>
              </view>
            </view>
            <view class="group-status">
              <view
                class="network-share"
                :class="getNetworkShareClass(group.networkShare)"
              >{{ group.networkShare }}%</view>
              <view class="status-labels">
                <u-tag v-if="group.isLowQuality == 1" text="低质态" type="warning" size="mini" />
                <u-tag
                  v-if="group.opportunities > 0"
                  :text="`${group.opportunities}商机`"
                  type="primary"
                  size="mini"
                />
              </view>
            </view>
          </view>

          <!-- 集团数据指标 -->
          <view class="group-metrics">
            <view class="metric-item">
              <text class="metric-label">单位人数</text>
              <text class="metric-value">{{ group.totalMembers }}</text>
            </view>
            <view class="metric-item">
              <text class="metric-label">本网成员</text>
              <text class="metric-value">{{ group.networkMembers }}</text>
            </view>
            <view class="metric-item">
              <text class="metric-label">5G成员</text>
              <text class="metric-value">{{ group.members5G }}</text>
            </view>
            <view class="metric-item">
              <text class="metric-label">宽带成员</text>
              <text class="metric-value">{{ group.broadbandMembers }}</text>
            </view>
          </view>
        </view>
      </scroll-view>

      <!-- 空状态提示 -->
      <view class="empty-tips" v-else>
        <u-empty mode="list" text="暂无符合条件的集团单位" marginTop="80" iconSize="120"></u-empty>
      </view>
    </view>
  </view>
</template>

<script>
import {
  logBusinessOperation,
  LOG_ACTION,
  TARGET_TYPE
} from "@/utils/logger.js";

import {
  getIndustryIcon,
  getIndustryColor,
  getIndustryTagClass,
  getIndustryAvatarClass,
  getNetworkShareClass
} from "@/utils/industry-utils.js";

export default {
  data() {
    return {
      searchKeyword: "",
      activeTagIndex: 0,
      totalGroups: 0,
      groupList: [],
      filteredGroups: [],
      filterTags: [
        {
          name: "全部",
          icon: "grid",
          color: "#007aff",
          class: "tag-all",
          count: 0
        },
        {
          name: "政府机构",
          icon: "zhihu-circle-fill",
          color: "#19be6b",
          class: "tag-government",
          count: 0
        },
        {
          name: "教育",
          icon: "bookmark",
          color: "#ff9900",
          class: "tag-education",
          count: 0
        },
        {
          name: "医疗",
          icon: "heart",
          color: "#f56c6c",
          class: "tag-medical",
          count: 0
        }
      ],
      isLowQualityFilter: 0,
      lowQualityCount: 0
    };
  },
  onLoad() {
    // 获取行业列表
    this.getIndustryList();

    // 获取集团数据
    this.getGroupData();
  },
  methods: {
    // 获取行业列表
    getIndustryList() {
      uni.showLoading({
        title: "加载中..."
      });

      // 请求行业列表接口
      this.$http
        .sendRequest("zhanke/industry_list", "POST", {})
        .then(res => {
          uni.hideLoading();
          console.log("行业列表API返回:", res.data);

          if (res.data && res.data.code === 200) {
            const list = res.data.data || [];

            // 将接口返回的数据格式化为组件需要的格式
            if (list.length > 0) {
              // 更新标签列表，仅保留"全部"标签
              const newTags = [
                this.filterTags[0], // 全部
                ...list.map(item => ({
                  name: item.name,
                  icon: this.getIndustryIcon(item.name),
                  color: this.getIndustryColor(item.name),
                  class: this.getIndustryClass(item.name),
                  count: 0
                }))
              ];

              this.filterTags = newTags;
            }
          } else {
            console.log("获取行业列表失败，使用默认数据");
            // 使用默认数据（已在data中定义）
          }
        })
        .catch(err => {
          uni.hideLoading();
          console.error("获取行业列表出错:", err);

          uni.showToast({
            title: "网络请求失败，使用默认行业分类",
            icon: "none"
          });
        });
    },

    // 根据行业名称获取图标
    getIndustryIcon(industry) {
      return getIndustryIcon(industry);
    },

    // 根据行业名称获取颜色
    getIndustryColor(industry) {
      return getIndustryColor(industry);
    },

    // 根据行业名称获取CSS类名
    getIndustryClass(industry) {
      return getIndustryTagClass(industry);
    },

    // 获取集团数据
    getGroupData() {
      uni.showLoading({
        title: "加载中..."
      });

      // 调用API获取集团列表
      this.$http
        .sendRequest("zhanke/group_list", "POST", {
          page: 1,
          limit: 50,
          industry:
            this.activeTagIndex === 0
              ? ""
              : this.filterTags[this.activeTagIndex].name,
          isLowQuality: this.isLowQualityFilter,
          keyword: this.searchKeyword
        })
        .then(res => {
          uni.hideLoading();
          console.log("集团列表API返回:", res.data);

          if (res.data && res.data.code === 200) {
            const list = res.data.data.list || [];
            this.totalGroups = res.data.data.total || list.length;

            // 格式化API返回的数据
            this.groupList = list.map(item => {
              // 计算本网份额
              const networkShare =
                item.totalMembers > 0
                  ? Math.round((item.networkMembers / item.totalMembers) * 100)
                  : 0;

              return {
                id: item.id,
                name: item.name,
                code: item.code,
                district: item.district || "未知",
                industry: item.industry || "其他",
                industryChain: item.industryChain || "",
                manager: item.manager || "",
                totalMembers: item.totalMembers || 0,
                networkMembers: item.networkMembers || 0,
                networkShare: networkShare,
                members5G: item.members5G || 0,
                broadbandMembers: item.broadbandMembers || 0,
                terminal5GMembers: item.terminal5GMembers || 0,
                isLowQuality: item.isLowQuality === 1,
                opportunities: item.opportunities || 0
              };
            });

            this.updateTagCounts();
            this.filteredGroups = [...this.groupList];
          } else {
            // 请求失败时使用空数组
            this.groupList = [];
            this.filteredGroups = [];
            this.totalGroups = 0;

            uni.showToast({
              title: res.data.msg || "获取集团列表失败",
              icon: "none"
            });
          }
        })
        .catch(err => {
          uni.hideLoading();
          console.error("获取集团列表出错:", err);

          // 请求出错时使用空数组
          this.groupList = [];
          this.filteredGroups = [];
          this.totalGroups = 0;

          uni.showToast({
            title: "网络请求失败，请稍后再试",
            icon: "none"
          });
        });
    },

    // 更新标签统计
    updateTagCounts() {
      // 设置"全部"标签的数量
      this.filterTags[0].count = this.groupList.length;

      // 更新每个行业标签的数量
      for (let i = 1; i < this.filterTags.length; i++) {
        const industry = this.filterTags[i].name;
        this.filterTags[i].count = this.groupList.filter(
          item => item.industry === industry
        ).length;
      }

      // 更新低质态数量
      this.lowQualityCount = this.groupList.filter(
        item => item.isLowQuality === 1
      ).length;
    },

    // 按标签筛选
    filterByTag(index) {
      this.activeTagIndex = index;

      // 如果不是全部标签，根据行业筛选
      if (index !== 0) {
        // 行业标签
        this.getFilteredData(
          this.filterTags[index].name,
          this.isLowQualityFilter
        );
      } else {
        // 全部标签，重新获取全部数据（保持低质态筛选条件）
        this.getGroupData();
      }
    },

    // 获取筛选后的数据
    getFilteredData(industry, isLowQuality) {
      uni.showLoading({
        title: "加载中..."
      });

      this.$http
        .sendRequest("zhanke/group_list", "POST", {
          page: 1,
          limit: 50,
          industry: industry,
          isLowQuality: isLowQuality,
          keyword: this.searchKeyword
        })
        .then(res => {
          uni.hideLoading();

          if (res.data && res.data.code === 200) {
            const list = res.data.data.list || [];

            // 格式化API返回的数据
            this.filteredGroups = list.map(item => {
              // 计算本网份额
              const networkShare =
                item.totalMembers > 0
                  ? Math.round((item.networkMembers / item.totalMembers) * 100)
                  : 0;

              return {
                id: item.id,
                name: item.name,
                code: item.code,
                district: item.district || "未知",
                industry: item.industry || "其他",
                industryChain: item.industryChain || "",
                manager: item.manager || "",
                totalMembers: item.totalMembers || 0,
                networkMembers: item.networkMembers || 0,
                networkShare: networkShare,
                members5G: item.members5G || 0,
                broadbandMembers: item.broadbandMembers || 0,
                terminal5GMembers: item.terminal5GMembers || 0,
                isLowQuality:
                  item.isLowQuality === 1 || networkShare <= 45 ? 1 : 0,
                opportunities: item.opportunities || 0
              };
            });
          } else {
            // 请求失败时使用空数组
            this.filteredGroups = [];

            uni.showToast({
              title: res.data.msg || "获取筛选数据失败",
              icon: "none"
            });
          }
        })
        .catch(err => {
          uni.hideLoading();
          console.error("获取筛选数据出错:", err);

          // 请求出错时使用空数组
          this.filteredGroups = [];

          uni.showToast({
            title: "网络请求失败，请稍后再试",
            icon: "none"
          });
        });
    },

    // 搜索
    onSearch() {
      if (!this.searchKeyword.trim()) {
        this.filterByTag(this.activeTagIndex);
        return;
      }

      // 通过API搜索
      uni.showLoading({
        title: "搜索中..."
      });

      this.$http
        .sendRequest("zhanke/group_list", "POST", {
          page: 1,
          limit: 50,
          keyword: this.searchKeyword,
          industry:
            this.activeTagIndex > 0
              ? this.filterTags[this.activeTagIndex].name
              : "",
          isLowQuality: this.isLowQualityFilter
        })
        .then(res => {
          uni.hideLoading();

          if (res.data && res.data.code === 200) {
            const list = res.data.data.list || [];

            // 格式化API返回的数据
            this.filteredGroups = list.map(item => {
              // 计算本网份额
              const networkShare =
                item.totalMembers > 0
                  ? Math.round((item.networkMembers / item.totalMembers) * 100)
                  : 0;

              return {
                id: item.id,
                name: item.name,
                code: item.code,
                district: item.district || "未知",
                industry: item.industry || "其他",
                industryChain: item.industryChain || "",
                manager: item.manager || "",
                totalMembers: item.totalMembers || 0,
                networkMembers: item.networkMembers || 0,
                networkShare: networkShare,
                members5G: item.members5G || 0,
                broadbandMembers: item.broadbandMembers || 0,
                terminal5GMembers: item.terminal5GMembers || 0,
                isLowQuality:
                  item.isLowQuality === 1 || networkShare <= 45 ? 1 : 0,
                opportunities: item.opportunities || 0
              };
            });
          } else {
            // 请求失败时使用空数组
            this.filteredGroups = [];

            uni.showToast({
              title: res.data.msg || "搜索失败",
              icon: "none"
            });
          }
        })
        .catch(err => {
          uni.hideLoading();
          console.error("搜索出错:", err);

          // 请求出错时使用空数组
          this.filteredGroups = [];

          uni.showToast({
            title: "网络请求失败，请稍后再试",
            icon: "none"
          });
        });
    },

    // 查看集团详情
    viewGroupDetail(group) {
      uni.navigateTo({
        url: `/pages/group/detail?groupCode=${group.code}`
      });

      // 记录查看集团详情的操作日志
      logBusinessOperation(
        LOG_ACTION.VIEW,
        TARGET_TYPE.GROUP,
        { id: group.id, name: group.name },
        `查看了集团单位"${group.name}"的详细信息`
      );
    },

    // 获取行业对应的样式类
    getIndustryClass(industry) {
      return getIndustryAvatarClass(industry);
    },

    // 获取本网份额对应的样式类
    getNetworkShareClass(share) {
      return getNetworkShareClass(share);
    },

    // 处理低质态筛选开关变化
    onLowQualityFilterChange(value) {
      this.isLowQualityFilter = value ? 1 : 0;
      // 更新当前视图中的集团列表
      if (this.activeTagIndex > 0) {
        this.getFilteredData(
          this.filterTags[this.activeTagIndex].name,
          this.isLowQualityFilter
        );
      } else {
        this.getGroupData();
      }
    }
  }
};
</script>

<style>
.group-archive-container {
  min-height: 100vh;
  background-color: #f8f9fc;
  padding-bottom: 30px;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen,
    Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
}

/* 头部样式 */
.page-header {
  background: linear-gradient(135deg, #0078ff, #1546a3);
  padding: 60px 20px 25px;
  color: #ffffff;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.15);
  border-radius: 0 0 20px 20px;
  position: relative;
  overflow: hidden;
}

.page-header::after {
  content: "";
  position: absolute;
  width: 150px;
  height: 150px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 50%;
  bottom: -50px;
  right: -50px;
  z-index: 1;
}

.page-header::before {
  content: "";
  position: absolute;
  width: 80px;
  height: 80px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 50%;
  top: 20px;
  left: 30px;
  z-index: 1;
}

.page-title {
  font-size: 26px;
  font-weight: 700;
  letter-spacing: 0.5px;
  position: relative;
  z-index: 2;
}

.page-subtitle {
  font-size: 15px;
  opacity: 1;
  margin-top: 8px;
  position: relative;
  z-index: 2;
}

/* 搜索和筛选区域 */
.search-filter-area {
  padding: 20px 15px;
  background-color: #ffffff;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
  border-radius: 15px;
  margin: -15px 15px 15px;
  position: relative;
  z-index: 10;
}

.search-box {
  margin-bottom: 18px;
  position: relative;
}

.search-box /deep/ .u-search {
  padding: 0;
  height: 40px !important;
}

.search-box /deep/ .u-search__content {
  background-color: #f8f9fc;
  height: 40px !important;
}

.search-box /deep/ .u-search__action {
  color: #0078ff;
  font-size: 14px;
  width: 50px;
  padding-left: 0;
}

.filter-tags {
  width: 100%;
  white-space: nowrap;
}

.tags-container {
  display: flex;
  padding: 8px 0;
}

.filter-tag {
  display: inline-flex;
  align-items: center;
  padding: 8px 14px;
  margin-right: 12px;
  background-color: #f8f9fa;
  border-radius: 12px;
  font-size: 14px;
  color: #606266;
  transition: all 0.3s ease;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.03);
  border: 1px solid rgba(232, 234, 237, 0.8);
}

.tag-with-shadow {
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
}

.filter-tag.active {
  background-color: #0078ff;
  color: #ffffff;
  transform: translateY(-2px);
}

.tag-icon {
  width: 28px;
  height: 28px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 8px;
  transition: all 0.3s ease;
}

.tag-all {
  background-color: #e1f2ff;
}
.tag-government {
  background-color: #d7f8e8;
}
.tag-education {
  background-color: #fff1e0;
}
.tag-medical {
  background-color: #ffeded;
}
.tag-finance {
  background-color: #f3e5f5;
}
.tag-transport {
  background-color: #e3f2fd;
}
.tag-industry {
  background-color: #fff3e0;
}
.tag-agriculture {
  background-color: #e8f5e9;
}
.tag-innovation {
  background-color: #e0f2f1;
}
.tag-fusion {
  background-color: #eceff1;
}
.tag-legal {
  background-color: #f3e5f5;
}
.tag-default {
  background-color: #f5f5f5;
}

.filter-tag.active .tag-all,
.filter-tag.active .tag-government,
.filter-tag.active .tag-education,
.filter-tag.active .tag-medical,
.filter-tag.active .tag-finance,
.filter-tag.active .tag-transport,
.filter-tag.active .tag-industry,
.filter-tag.active .tag-agriculture,
.filter-tag.active .tag-innovation,
.filter-tag.active .tag-fusion,
.filter-tag.active .tag-legal,
.filter-tag.active .tag-default {
  background-color: rgba(255, 255, 255, 0.2);
}

.tag-count {
  margin-left: 6px;
  font-size: 12px;
  background-color: rgba(0, 0, 0, 0.06);
  padding: 1px 6px;
  border-radius: 10px;
  min-width: 20px;
  text-align: center;
}

.filter-tag.active .tag-count {
  background-color: rgba(255, 255, 255, 0.2);
}

/* 低质态筛选样式 */
.low-quality-filter {
  display: flex;
  align-items: center;
  padding: 0 20px 15px;
  background-color: #ffffff;
}

.low-quality-text {
  margin-left: 10px;
  font-size: 14px;
  color: #606266;
}

.low-quality-count {
  margin-left: 6px;
  font-size: 12px;
  background-color: #ffe6d9;
  color: #ff9900;
  padding: 1px 6px;
  border-radius: 10px;
  min-width: 20px;
  text-align: center;
}

/* 集团列表区域 */
.group-list-area {
  padding: 15px;
  position: relative;
}

.group-list-area::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-image: radial-gradient(
    rgba(0, 120, 255, 0.08) 1px,
    transparent 1px
  );
  background-size: 20px 20px;
  pointer-events: none;
  z-index: -1;
}

.group-list {
  height: calc(100vh - 230px);
  padding: 5px 2px;
}

.group-card {
  animation: fadeIn 0.5s ease;
  transition: all 0.3s cubic-bezier(0.16, 1, 0.3, 1);
  will-change: transform, box-shadow;
  background-color: #ffffff;
  border-radius: 12px;
  padding: 18px;
  margin-bottom: 16px;
  box-shadow: 0 6px 18px rgba(0, 120, 255, 0.12);
  border: 1px solid rgba(232, 234, 237, 0.9);
  position: relative;
  overflow: hidden;
}

.group-card:hover {
  transform: translateY(-3px) scale(1.01);
  box-shadow: 0 12px 24px rgba(0, 120, 255, 0.15);
}

.group-info {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.group-avatar {
  width: 50px;
  height: 50px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  font-size: 20px;
  font-weight: bold;
  color: #ffffff;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
}

.avatar-government {
  background: linear-gradient(135deg, #0abd5a, #07964d);
}
.avatar-education {
  background: linear-gradient(135deg, #ff9500, #f57c00);
}
.avatar-medical {
  background: linear-gradient(135deg, #f55c5c, #e53935);
}
.avatar-finance {
  background: linear-gradient(135deg, #9c27b0, #7b1fa2);
}
.avatar-transport {
  background: linear-gradient(135deg, #3498db, #2980b9);
}
.avatar-industry {
  background: linear-gradient(135deg, #e67e22, #d35400);
}
.avatar-agriculture {
  background: linear-gradient(135deg, #2ecc71, #27ae60);
}
.avatar-innovation {
  background: linear-gradient(135deg, #1abc9c, #16a085);
}
.avatar-fusion {
  background: linear-gradient(135deg, #34495e, #2c3e50);
}
.avatar-legal {
  background: linear-gradient(135deg, #8e44ad, #6c3483);
}
.avatar-default {
  background: linear-gradient(135deg, #607d8b, #455a64);
}

.group-details {
  flex: 1;
}

.group-name {
  font-size: 17px;
  font-weight: bold;
  color: #222222;
  margin-bottom: 5px;
}

.group-meta {
  font-size: 12px;
  color: #606266;
  display: flex;
  align-items: center;
}

.group-district::after {
  content: "•";
  margin: 0 5px;
}

.group-status {
  text-align: right;
}

.network-share {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 8px;
  position: relative;
}

.share-low {
  color: #f55c5c;
}
.share-medium {
  color: #ff9500;
}
.share-high {
  color: #0abd5a;
}

.status-labels {
  display: flex;
  justify-content: flex-end;
  flex-wrap: wrap;
  margin-top: 5px;
}

.status-labels > view {
  margin-left: 6px;
  transform: scale(0.95);
}

.group-metrics {
  display: flex;
  justify-content: space-between;
  background-color: #f8fafd;
  border-radius: 10px;
  padding: 12px;
  margin-top: 2px;
  border: 1px solid rgba(232, 234, 237, 0.8);
}

.metric-item {
  text-align: center;
  flex: 1;
  padding: 5px 0;
}

.metric-label {
  font-size: 12px;
  color: #606266;
  display: block;
  margin-bottom: 5px;
}

.metric-value {
  font-size: 16px;
  color: #222222;
  font-weight: bold;
}

/* 空状态提示 */
.empty-tips {
  display: flex;
  justify-content: center;
  padding: 50px 0;
  background-color: rgba(248, 249, 252, 0.6);
  border-radius: 12px;
  margin: 20px 0;
}

/* 卡片动画和交互效果 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style> 